package com.ruicar.afs.cloud.bizcommon.print.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.bizcommon.dto.print.TemplateDto;
import com.ruicar.afs.cloud.bizcommon.print.entity.ComPrintFormFieldMapping;
import com.ruicar.afs.cloud.bizcommon.print.mapper.ComPrintFormFieldMappingMapper;
import com.ruicar.afs.cloud.bizcommon.print.service.ComPrintFormFieldMappingService;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * 打印模板字段映射服务
 *
 * @author phong
 * @version 1.0
 * @created 2020/6/8 11:40
 */
@Service
@Slf4j
public class ComPrintFormFieldMappingServiceImpl extends ServiceImpl<ComPrintFormFieldMappingMapper, ComPrintFormFieldMapping>
        implements ComPrintFormFieldMappingService {

    @Override
    public Boolean saveFieldMapping(ComPrintFormFieldMapping vo) {
        // 映射字段不能重复
        testKey(vo);
        // 数据保存
        this.baseMapper.insert(vo);
        return Boolean.TRUE;
    }

    @Override
    public Boolean delFieldMapping(String id) {
        this.baseMapper.deleteById(Long.valueOf(id));
        return Boolean.TRUE;
    }

    @Override
    public Boolean modifyFieldMapping(ComPrintFormFieldMapping vo) {
        testKey(vo);
        this.baseMapper.updateById(vo);
        return Boolean.TRUE;
    }

    public List<ComPrintFormFieldMapping> listForPrintFormId(String printFormId) {
        List<ComPrintFormFieldMapping> list =
                this.list(Wrappers.<ComPrintFormFieldMapping>lambdaQuery()
                        .eq(ComPrintFormFieldMapping::getPrintFormId, printFormId));
        return list;
    }

    @Override
    public IResponse query(QueryCondition<TemplateDto> queryCondition) {

        Page<ComPrintFormFieldMapping> page = this.baseMapper.selectPage(
                new Page<ComPrintFormFieldMapping>(queryCondition.getPageNumber(), queryCondition.getPageSize()),
                Wrappers.<ComPrintFormFieldMapping>lambdaQuery()
                        .eq(ComPrintFormFieldMapping::getTemplateId, queryCondition.getCondition().getTemplateId()));

        return IResponse.success(page);

    }

    private void testKey(ComPrintFormFieldMapping vo) {
        long count = this.baseMapper.selectCount(Wrappers.<ComPrintFormFieldMapping>lambdaQuery()
                .eq(ComPrintFormFieldMapping::getPrintFormId, vo.getPrintFormId())
                .eq(ComPrintFormFieldMapping::getMappingFieldId, vo.getMappingFieldId()));
        Assert.isTrue(count == 0, "编号[" + vo.getPrintFormId() + "]的模板字段[" + vo.getMappingFieldId() + "]["
                + vo.getMappingFieldName() + "]重复");
    }


}
